const express = require('express');
const app = express();
const ejs = require('ejs');
const expressWS = require('express-ws');
const tcpServer = require('./tcpServer');
const router = express.Router();
const { v4 } = require('uuid');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.set('views', './views');
app.set('view engine', 'ejs');
app.engine('html', ejs.renderFile);
expressWS(app); 

// tcp实例
const tcpServerIns = new tcpServer();

router.ws('/watch', function(ws, req) {
  const uniqId = v4();
  ws.clientId = uniqId;
  tcpServerIns.addClient({
    id: uniqId,
    ws: ws,
  });
  ws.on('close', () => {
    tcpServerIns.removeClient(ws.clientId);
  })
});

app.use('/tcp', router);

app.get('/', function (req, res) {
  res.render('index.html');
})

app.get('/sendDic', function(req, res) {
  const {
    dist, dic
  } = req.query
  // 7B0002A202A67D
  tcpServerIns.writeDataByMac(dist, dic).then(function() {
    res.send({
      code: 200,
      msg: '发送成功'
    })
  }, function(err) {
    res.send({
      code: -1,
      msg: err,
    })
  });
})
 
app.listen(3000, function() {
  console.log(`listening on port 3000`)
})
